package fina2.dcs.fis;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.context.ContextHelper;
import fina2.dcs.i18n.LanguageSession;
import fina2.dcs.system.SysString;
import fina2.dcs.system.SysStringLocal;
import fina2.dcs.system.SysStringPk;

@Stateful
@Scope(ScopeType.SESSION)
@Name("bnkBranchSession")
@LocalBinding(jndiBinding = "BankBranchSession/local")
@SuppressWarnings("unchecked")
@AutoCreate
public class BankBranchSession implements BankBranchLocal, Serializable {

	@PersistenceContext
	private EntityManager em;
	
	
	@Logger
	private Log log;

	private InitialContext ic = null;

	private SysStringLocal sysStringLocal = null;

	private RegionLocal regLocal = null;

	public void init() {
		try {
			ic = ContextHelper.getInitialContext();
			sysStringLocal = ContextHelper.injectSysStringLocal(ic);
			regLocal = ContextHelper.injectRegionLocal(ic);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public List<BankBranch> loadBranchesByBankId(BigDecimal bankId) {
		List<BankBranch> branches = null;
		try {
			ic = ContextHelper.getInitialContext();
			sysStringLocal = ContextHelper.injectSysStringLocal(ic);
			regLocal = ContextHelper.injectRegionLocal(ic);
			branches = em.createQuery("FROM " + BankBranch.class.getName() + " b WHERE b.bankId=:bankId").setParameter("bankId", bankId).getResultList();
			if (branches != null) {
				for (int i = 0; i < branches.size(); i++) {
					SysString ss = sysStringLocal.findByPk(new SysStringPk(branches.get(i).getShortNameStrId(), LanguageSession.langId));
					branches.get(i).setShortName((ss != null) ? ss.getValue() : null);
					branches.get(i).setRegion(regLocal.findById(branches.get(i).getBankRegionStrId()));
				}
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return branches;
	}

	@Remove
	@Destroy
	public void remove() {

	}

}
